package com.ruoyi.business.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.bizsys.domain.ExtMonnifyOrder;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

@Slf4j
public class MonnifyUtils {

    /**
     * 以webhook回调记录报文添加，设置ExtMonnifyOrder记录
     *
     * @param jsonObject
     * @param custNo
     * @return
     */
    public static ExtMonnifyOrder setExtMonnifyOrderWebHook(JSONObject jsonObject, String custNo) {
        ExtMonnifyOrder extMonnifyOrder = new ExtMonnifyOrder();
        extMonnifyOrder.setCustNo(custNo);
        if (jsonObject != null) {

            extMonnifyOrder.setEventType(jsonObject.getString("eventType"));
            extMonnifyOrder.setTransactionReference(jsonObject.getString("transactionReference"));
            extMonnifyOrder.setPaymentReference(jsonObject.getString("paymentReference"));
            extMonnifyOrder.setPaymentStatus(jsonObject.getString("paymentStatus"));
            if (jsonObject.getJSONObject("metaData") != null) {
                extMonnifyOrder.setMetaDataName(jsonObject.getJSONObject("metaData").getString("name"));
                extMonnifyOrder.setMetaDataAge(jsonObject.getJSONObject("metaData").getString("age"));
            }

            if (jsonObject.getJSONObject("customer") != null) {
                extMonnifyOrder.setCustomerEmail(jsonObject.getJSONObject("customer").getString("email"));
                extMonnifyOrder.setCustomerName(jsonObject.getJSONObject("customer").getString("name"));
            }

            //if(jsonObject.getJSONObject("accountDetails")!=null){
            JSONArray paymentSources = jsonObject.getJSONArray("paymentSourceInformation");
            if (paymentSources != null && paymentSources.size() > 0) {
                JSONObject paymentSourceInformation = paymentSources.getJSONObject(0);
                extMonnifyOrder.setAccountDetailsAccountName(paymentSourceInformation.getString("accountName"));
                // extMonnifyOrder.setAccountDetailsAccountNumber(paymentSourceInformation.getString("accountNumber"));
                // extMonnifyOrder.setAccountDetailsBankCode(paymentSourceInformation.getString("bankCode"));
                extMonnifyOrder.setAccountDetailsAmountPaid(paymentSourceInformation.getString("amountPaid"));
            }

            JSONObject destinationAccountInformation = jsonObject.getJSONObject("destinationAccountInformation");
            if (destinationAccountInformation != null) {
                extMonnifyOrder.setAccountDetailsAccountName(destinationAccountInformation.getString("accountName"));
                extMonnifyOrder.setAccountDetailsAccountNumber(destinationAccountInformation.getString("accountNumber"));
                extMonnifyOrder.setAccountDetailsBankCode(destinationAccountInformation.getString("bankCode"));
            }

            extMonnifyOrder.setCardDetails(jsonObject.getString("cardDetails"));
            extMonnifyOrder.setProductType(jsonObject.getJSONObject("product").getString("type"));
            extMonnifyOrder.setProductReference(jsonObject.getJSONObject("product").getString("reference"));
            extMonnifyOrder.setPaymentMethod(jsonObject.getString("paymentMethod"));
            extMonnifyOrder.setCurrency(jsonObject.getString("currency"));
            extMonnifyOrder.setPaymentDescription(jsonObject.getString("paymentDescription"));

            Date paidOn;
            try {
                paidOn = DateUtils.dateFormatConversion("yyyy-MM-dd HH:mm:ss.SSS", jsonObject.getString("paidOn"));
            } catch (Exception e) {
                paidOn = new Date();
            }

            extMonnifyOrder.setPaidOn(DateUtils.formatDate(paidOn, DateUtils.YYYY_MM_DD_HH_MM_SS));
            extMonnifyOrder.setSettlementAmount(jsonObject.getBigDecimal("settlementAmount"));
            extMonnifyOrder.setTotalPayable(jsonObject.getBigDecimal("totalPayable"));
            extMonnifyOrder.setAmountPaid(jsonObject.getBigDecimal("amountPaid"));
            extMonnifyOrder.setCustNo(custNo);
            extMonnifyOrder.setType(BizConstants.MONNFIY_ORDER_TYPE_WEBHOOK_TTS);
        }
        log.info("Monnify paidOn = {}", extMonnifyOrder.getPaidOn());
        return extMonnifyOrder;
    }

    /**
     * 以查询接口记录报文添加，设置ExtMonnifyOrder记录
     *
     * @param jsonObject
     * @param custNo
     * @return
     */
    public static ExtMonnifyOrder setExtMonnifyOrderInterface(JSONObject jsonObject, String accountReference, String custNo) {
        //1.添加进虚拟账户订单表
        ExtMonnifyOrder extMonnifyOrder = new ExtMonnifyOrder();
        extMonnifyOrder.setProductReference(accountReference);
        extMonnifyOrder.setCustNo(custNo);
        if (jsonObject.getJSONObject("customerDTO") != null) {
            extMonnifyOrder.setCustomerEmail(jsonObject.getJSONObject("customerDTO").getString("email"));
            extMonnifyOrder.setCustomerName(jsonObject.getJSONObject("customerDTO").getString("name"));
        }
        extMonnifyOrder.setPaymentMethod(jsonObject.getString("paymentMethod"));
        extMonnifyOrder.setTotalPayable(jsonObject.getBigDecimal("amount"));
        extMonnifyOrder.setPaymentDescription(jsonObject.getString("paymentDescription"));
        extMonnifyOrder.setSettlementAmount(jsonObject.getBigDecimal("amountPaid").subtract(jsonObject.getBigDecimal("fee")));
        extMonnifyOrder.setPaymentStatus(jsonObject.getString("paymentStatus"));
        extMonnifyOrder.setTransactionReference(jsonObject.getString("transactionReference"));
        extMonnifyOrder.setPaymentReference(jsonObject.getString("paymentReference"));
        extMonnifyOrder.setAmountPaid(jsonObject.getBigDecimal("amountPaid"));
        extMonnifyOrder.setType(BizConstants.MONNFIY_ORDER_TYPE_TTS);
        extMonnifyOrder.setCurrency(jsonObject.getString("currencyCode"));
        extMonnifyOrder.setProductType(jsonObject.getString("collectionChannel"));

        try {
            if (StringUtils.isNotBlank(jsonObject.getString("completedOn"))) {
                Date completedOn = DateUtils.parseUTCText(jsonObject.getString("completedOn"));
                // 服务器时区为 UTC + 0，此处无需 -8
                // Date date = DateUtils.addHours(completedOn, -8);
                extMonnifyOrder.setPaidOn(DateUtils.formatDate(completedOn, "yyyy-MM-dd HH:mm:ss"));
            }
        } catch (Exception e) {
            log.error("monnify order pay time parse Error：", e);
        }

        return extMonnifyOrder;
    }

    public static String SHA(final String strText) {
        // 返回值
        String strResult = null;

        // 是否是有效字符串
        if (strText != null && strText.length() > 0) {
            try {
                // SHA 加密开始
                // 创建加密对象 并傳入加密類型
                MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
                // 传入要加密的字符串
                messageDigest.update(strText.getBytes());
                // 得到 byte 類型结果
                byte byteBuffer[] = messageDigest.digest();

                // 將 byte 轉換爲 string
                StringBuffer strHexString = new StringBuffer();
                // 遍歷 byte buffer
                for (int i = 0; i < byteBuffer.length; i++) {
                    String hex = Integer.toHexString(0xff & byteBuffer[i]);
                    if (hex.length() == 1) {
                        strHexString.append('0');
                    }
                    strHexString.append(hex);
                }
                // 得到返回結果
                strResult = strHexString.toString();
            } catch (NoSuchAlgorithmException e) {
                return null;
            }
        }

        return strResult;
    }
}
